package cn.whb.hrm.service.impl;

import cn.whb.hrm.domain.LoginUser;
import cn.whb.hrm.domain.VipUser;
import cn.whb.hrm.dto.RegisterDto;
import cn.whb.hrm.feign.RegisterFeignClient;
import cn.whb.hrm.mapper.VipUserMapper;
import cn.whb.hrm.service.IVipUserService;
import cn.whb.hrm.util.AjaxResult;
import cn.whb.hrm.util.BitStatesUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author whb
 * @since 2021-12-25
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RegisterFeignClient feignClient;
    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult register(@Valid RegisterDto dto) {
        //非空校验交个jsr303
        //校验验证码
        String smsCode = dto.getSmsCode();
        Object code = redisTemplate.opsForValue().get("REGIST::" + dto.getMobile());
        if (code==null){
            throw new RuntimeException("验证码已过期，请重新输入");
        }
        if (!smsCode.equals(code.toString())){
            throw new RuntimeException("验证码错误，请重新输入");
        }
        //保存loginuser信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(dto.getMobile());
        loginUser.setPassword(dto.getPassword());
        AjaxResult result = feignClient.register(loginUser);
        if (result.isSuccess()){
            Integer id = (Integer) result.getResultObj();
            VipUser vipUser = new VipUser();
            vipUser.setLoginId(Long.valueOf(id));
            vipUser.setPhone(dto.getMobile());
            vipUser.setCreateTime(System.currentTimeMillis());
            vipUser.setPassword(dto.getPassword());
            //bitState
            long state = BitStatesUtils.OP_REGISTED;
            state=BitStatesUtils.addState(state, BitStatesUtils.OP_ACTIVED);
            state=BitStatesUtils.addState(state,BitStatesUtils.OP_AUTHED_PHONE);
            vipUser.setBitState(state);
            //保存用户信息
            vipUserMapper.insert(vipUser);
        }
        return result;
    }
}
